import { Request, Response } from 'express';
import groupService from '../services/group.service';
import {
    CreateGroupInput,
    GetGroupInput,
    InviteFriendInput,
    RemoveMemberInput,
    UpdateGroupInput
} from '../schemas/group.schemas';
import generateRandomAccount from '../utils/account';
import processMessage, { sendGroupMessage, sendUserMessage } from '../websocket/process';

import { MessageType } from '@prisma/client';

class GroupController {
    async getGroup(req: Request, res: Response) {
        const { userId } = req.auth;

        const { groupId } = req.query as GetGroupInput
        const groupInfo = await groupService.getGroup(groupId);

        if (!groupInfo || groupInfo.status !== 'NORMAL') {
            res.status(400).json({ message: 'group not found' });
            return;
        }

        const groupUser = await groupService.getGroupUser(groupId, userId);

        res.send({
            ...groupInfo,
            isMember: !!groupUser,
        });
    }

    async createGroup(req: Request, res: Response) {
        const { userId } = req.auth;
        const { name, description } = req.body as CreateGroupInput;

        const groupId = generateRandomAccount(10);
        const groupInfo = await groupService.createGroup({
            groupId,
            creatorId: userId,
            name,
            description
        });

        const groupUser = await groupService.createGroupMember(groupId, userId, 'OWNER');
        const newGroupMessage = {
            senderId: userId,
            groupId,
            content: '群聊创建好了，快来一起聊天吧。',
            type: 'SYSTEM' as MessageType,
        }
        await sendUserMessage('contact', groupUser, userId);
        await processMessage(newGroupMessage);
        res.send({ message: 'group created', groupInfo });
    }

    async inviteFriend(req: Request, res: Response) {
        const { userId } = req.auth;
        const { groupId, friendId } = req.body as InviteFriendInput;

        const groupUser = await groupService.getGroupUser(groupId, userId);
        if (!groupUser) {
            res.status(400).json({ message: 'you are not in group' });
            return;
        }

        const newGroupUser = await groupService.createGroupMember(groupId, friendId);
        const groupMessage = {
            senderId: userId,
            groupId,
            content: `${groupUser.user.nickname}邀请${newGroupUser.user.nickname}加入群聊`,
            type: 'SYSTEM' as MessageType,
        }
        await sendGroupMessage('contact', newGroupUser, groupId);
        await processMessage(groupMessage);

        res.send({ message: 'invite success' });
    }

    async disbandGroup(req: Request, res: Response) {
        const { userId } = req.auth;
        const { groupId } = req.query as GetGroupInput;

        const groupUser = await groupService.getGroupUser(groupId, userId);
        if (!groupUser || groupUser.role !== 'OWNER') {
            res.status(400).json({ message: 'you are not owner' });
            return;
        }

        const group = await groupService.disbandGroup(groupId);
        const groupMessage = {
            senderId: userId,
            groupId,
            content: '群聊已解散',
            type: 'SYSTEM' as MessageType,
        }
        await processMessage(groupMessage);
        res.send({ message: 'disband success' });
    }

    async removeMember(req: Request, res: Response) {
        const { userId } = req.auth;
        const { groupId, memberId } = req.query as RemoveMemberInput;

        const groupUser = await groupService.getGroupUser(groupId, memberId);
        if (!groupUser) {
            res.status(400).json({ message: 'member are not in group' });
            return;
        }

        if (memberId !== userId && groupUser.role == 'MEMBER') {
            res.status(400).json({ message: 'you are not admin' });
            return;
        }

        const newgroupUser = await groupService.removeGroupMember(groupId, memberId);
        await sendGroupMessage('contact', newgroupUser, groupId);
        res.send({ message: 'remove member success' });
    }

    async updateGroup(req: Request, res: Response) {
        const { userId } = req.auth;

        const { groupId, name, description } = req.body as UpdateGroupInput;

        const groupUser = await groupService.getGroupUser(groupId, userId);
        if (!groupUser || groupUser.role == 'MEMBER') {
            res.status(400).json({ message: 'you are not admin' });
            return;
        }

        await groupService.updateGroup(groupId, name, description);
        const groupMessage = {
            senderId: userId,
            groupId,
            content: `${groupUser.user.nickname}更新了群聊信息`,
            type: 'SYSTEM' as MessageType,
        }
        await processMessage(groupMessage);

        res.send({ message: 'update success' });
    }
}

const groupController = new GroupController();
export default groupController;
